/*
JIFArticleCRUD
PS a ajouter
*/
package cinescope2014.boundaries;

import cinescope2014.utilities.Globale;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author pascal
 */
public class JIFArticleCRUD extends javax.swing.JInternalFrame {

    private Connection icn;
    private DefaultTableModel idtm;
    private Map<String, String> imapJournalistes;
    private Map<String, String> imapFilms;

    /**
     * Creates new form JIFArticleCRUD
     */
    public JIFArticleCRUD() {
        initComponents();

        setTitle("CRUD Articles");

        try {
            // --- Connexion
//            Class.forName("org.gjt.mm.mysql.Driver");
//            String lsDSN = "jdbc:mysql://127.0.0.1:3306/cinescope2014";
//            icn = DriverManager.getConnection(lsDSN, "root", "");

            icn = Globale.getConnexion();

            String lsSQL;
            PreparedStatement lpst;
            ResultSet lrs;

//            lstSQL = icn.createStatement();
//            StringBuilder lsbSelect = new StringBuilder();
//            lsbSelect.append("SELECT j.id_journaliste, j.nom_journaliste, m.nom_media ");
//            lsbSelect.append(" FROM journaliste j NATURAL JOIN media m");
//            
//            ResultSet lrs = lstSQL.executeQuery(lsbSelect.toString());
//
//            Object[] tLigne;
//
//            idtm = (DefaultTableModel) jTableArticles.getModel();
//
//            while (lrs.next()) {
//                tLigne = new Object[3];
//
//                tLigne[0] = lrs.getString(1);
//                tLigne[1] = lrs.getString(2);
//                tLigne[2] = lrs.getString(3);
//
//                idtm.addRow(tLigne);
//            }
//
//            lrs.close();
            // Les journalistes
            imapJournalistes = new HashMap<>();
            lsSQL = "SELECT id_journaliste, nom_journaliste FROM journaliste ORDER BY nom_journaliste";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapJournalistes.put(lrs.getString(2), lrs.getString(1));
                jComboBoxJournalistes.addItem(lrs.getString(2));
            }
            lrs.close();
            lpst.close();

            // Les films
            imapFilms = new HashMap<>();
            lsSQL = "SELECT id_film, titre_film FROM film ORDER BY titre_film";
            lpst = icn.prepareStatement(lsSQL);
            lrs = lpst.executeQuery();
            while (lrs.next()) {
                imapFilms.put(lrs.getString(2), lrs.getString(1));
                jComboBoxFilms.addItem(lrs.getString(2));
            }
            lrs.close();
            lpst.close();

            jLabelMessage.setText("Okay !!!");

        } catch (SQLException ex) {
            jLabelMessage.setText(ex.getMessage());
        }

        setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableArticles = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jLabelMessage = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jTextFieldTitre = new javax.swing.JTextField();
        jComboBoxJournalistes = new javax.swing.JComboBox();
        jButtonAjouter = new javax.swing.JButton();
        jButtonSupprimer = new javax.swing.JButton();
        jButtonModifier = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabelID = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        jTextAreaTexte = new javax.swing.JTextArea();
        jTextFieldPhoto = new javax.swing.JTextField();
        jComboBoxFilms = new javax.swing.JComboBox();

        setClosable(true);
        setIconifiable(true);
        setMaximizable(true);
        setResizable(true);
        addInternalFrameListener(new javax.swing.event.InternalFrameListener() {
            public void internalFrameActivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosed(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameClosing(javax.swing.event.InternalFrameEvent evt) {
                formInternalFrameClosing(evt);
            }
            public void internalFrameDeactivated(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameDeiconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameIconified(javax.swing.event.InternalFrameEvent evt) {
            }
            public void internalFrameOpened(javax.swing.event.InternalFrameEvent evt) {
            }
        });

        jTableArticles.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jTableArticles.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableArticlesMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jTableArticles);

        jLabel1.setText("Titre");

        jLabelMessage.setText("Message");

        jLabel6.setText("Journaliste");

        jTextFieldTitre.setText("Le cinéma des années 90");

        jButtonAjouter.setText("Ajouter");
        jButtonAjouter.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonAjouterActionPerformed(evt);
            }
        });

        jButtonSupprimer.setText("Supprimer");
        jButtonSupprimer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSupprimerActionPerformed(evt);
            }
        });

        jButtonModifier.setText("Modifier");
        jButtonModifier.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModifierActionPerformed(evt);
            }
        });

        jLabel5.setText("ID");

        jLabelID.setForeground(new java.awt.Color(255, 0, 51));
        jLabelID.setText("ID");

        jLabel2.setText("Texte");

        jLabel3.setText("Film");

        jLabel4.setText("Photo");

        jTextAreaTexte.setColumns(20);
        jTextAreaTexte.setRows(5);
        jTextAreaTexte.setText("Très fort !!!");
        jScrollPane2.setViewportView(jTextAreaTexte);

        jTextFieldPhoto.setText("Années 90");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 568, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(jLabelMessage, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                .addGroup(layout.createSequentialGroup()
                                    .addComponent(jButtonAjouter)
                                    .addGap(18, 18, 18)
                                    .addComponent(jButtonModifier)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 23, Short.MAX_VALUE)
                                    .addComponent(jButtonSupprimer)))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(jLabel6)
                                    .addComponent(jLabel5)
                                    .addComponent(jLabel2)
                                    .addComponent(jLabel4)
                                    .addComponent(jLabel3))
                                .addGap(52, 52, 52)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                    .addComponent(jComboBoxJournalistes, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                    .addComponent(jLabelID, javax.swing.GroupLayout.PREFERRED_SIZE, 68, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jTextFieldTitre)
                                    .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 464, Short.MAX_VALUE)
                                    .addComponent(jTextFieldPhoto)
                                    .addComponent(jComboBoxFilms, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))))
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 115, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(jLabelID))
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jTextFieldTitre, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(11, 11, 11)
                        .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 113, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(18, 18, 18)
                        .addComponent(jLabel2)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 14, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(jTextFieldPhoto, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3)
                    .addComponent(jComboBoxFilms, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jComboBoxJournalistes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6))
                .addGap(18, 18, 18)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonAjouter)
                    .addComponent(jButtonModifier)
                    .addComponent(jButtonSupprimer))
                .addGap(18, 18, 18)
                .addComponent(jLabelMessage)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void formInternalFrameClosing(javax.swing.event.InternalFrameEvent evt) {//GEN-FIRST:event_formInternalFrameClosing
        //
//        try {
//            icn.close();
//        } catch (SQLException e) {
//            System.err.println(e.getMessage());
//        }
    }//GEN-LAST:event_formInternalFrameClosing

    private void jButtonAjouterActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonAjouterActionPerformed
        //
        try {
            String lsSQL;
            lsSQL = "INSERT INTO article(titre_article, texte_article, photo_article, id_journaliste, id_film) VALUES(?,?,?,?,?)";
            PreparedStatement lpst = icn.prepareStatement(lsSQL);

            lpst.setString(1, jTextFieldTitre.getText());
            lpst.setString(2, jTextAreaTexte.getText());
            lpst.setString(3, jTextFieldPhoto.getText());
            lpst.setString(4, imapJournalistes.get(jComboBoxJournalistes.getSelectedItem().toString()));
            lpst.setString(5, imapFilms.get(jComboBoxFilms.getSelectedItem().toString()));
//            System.out.println(jComboBoxDepartements.getSelectedItem().toString());
            lpst.executeUpdate();
            icn.commit();
            lpst.close();
            // Mise a jour de la jTable via le DTM
//            String[] tLigne = new String[3];
//            tLigne[0] = "";
//            tLigne[1] = jTextFieldTitre.getText();
//            tLigne[2] = jComboBoxJournalistes.getSelectedItem().toString();
//            idtm.addRow(tLigne);
            jLabelMessage.setText("Okay !!!");

        } catch (SQLException e) {
            jLabelMessage.setText("KO !!!!");
            System.out.println(e.getMessage());
        }
    }//GEN-LAST:event_jButtonAjouterActionPerformed

    private void jTableArticlesMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jTableArticlesMouseClicked
        //
        int liLigne = jTableArticles.getSelectedRow();

        jLabelID.setText(jTableArticles.getValueAt(liLigne, 0).toString());
        jTextFieldTitre.setText(jTableArticles.getValueAt(liLigne, 1).toString());
        jComboBoxJournalistes.setSelectedItem(jTableArticles.getValueAt(liLigne, 2).toString());
    }//GEN-LAST:event_jTableArticlesMouseClicked

    private void jButtonSupprimerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSupprimerActionPerformed
        //
        if (jTableArticles.getSelectedRow() == -1) {
            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
        } else {
            if (jLabelID.getText().equals("")) {
                idtm.removeRow(jTableArticles.getSelectedRow());
                jLabelMessage.setText("");
            } else {
                try {
                    String lsSQL;
                    lsSQL = "DELETE FROM article WHERE id_article=?";
                    lsSQL = "{CALL articleDelete(?)}";
                    PreparedStatement lpst = icn.prepareStatement(lsSQL);

                    lpst.setString(1, jLabelID.getText());

                    lpst.executeUpdate();
                    icn.commit();
                    lpst.close();
                    // Suppression dans la jTable via le DefalutTableModel
                    idtm.removeRow(jTableArticles.getSelectedRow());

                    jLabelMessage.setText("Okay !!!");

                } catch (SQLException e) {
                    jLabelMessage.setText("KO !!!!");
                    System.out.println(e.getMessage());
                }
            }
        }
    }//GEN-LAST:event_jButtonSupprimerActionPerformed

    private void jButtonModifierActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonModifierActionPerformed
        // 
        int liLigne = jTableArticles.getSelectedRow();
        if (liLigne == -1) {
            jLabelMessage.setText("Vous devez sélectionner une ligne !!!");
        } else {

            try {
                String lsSQL;
                lsSQL = "UPDATE article SET titre_article=?, texte_article=? WHERE id_article=?";
                PreparedStatement lpst = icn.prepareStatement(lsSQL);

                lpst.setString(1, jTextFieldTitre.getText());
                lpst.setString(2, jTextAreaTexte.getText());
                lpst.setString(3, jLabelID.getText());

                lpst.executeUpdate();
                icn.commit();
                lpst.close();
                // Modification dans la jTable
//                jTableVilles.setValueAt(jTextFieldCP.getText(), liLigne, 1);
//                jTableVilles.setValueAt(jTextFieldNom.getText(), liLigne, 2);
//                jTableVilles.setValueAt(jComboBoxDepartements.getSelectedItem(), liLigne, 3);
                idtm.setValueAt(jLabelID.getText(), liLigne, 0);
                idtm.setValueAt(jTextFieldTitre.getText(), liLigne, 1);
                idtm.setValueAt(jComboBoxJournalistes.getSelectedItem(), liLigne, 2);

                jLabelMessage.setText("Okay !!!");

            } catch (SQLException e) {
                jLabelMessage.setText("KO !!!!");
                System.out.println(e.getMessage());
            }

        }
    }//GEN-LAST:event_jButtonModifierActionPerformed


    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonAjouter;
    private javax.swing.JButton jButtonModifier;
    private javax.swing.JButton jButtonSupprimer;
    private javax.swing.JComboBox jComboBoxFilms;
    private javax.swing.JComboBox jComboBoxJournalistes;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabelID;
    private javax.swing.JLabel jLabelMessage;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jTableArticles;
    private javax.swing.JTextArea jTextAreaTexte;
    private javax.swing.JTextField jTextFieldPhoto;
    private javax.swing.JTextField jTextFieldTitre;
    // End of variables declaration//GEN-END:variables
}
